<?php

namespace App\Controller\Common;

use App\Base\ViewsInList;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class CMVCController
Controller Model View Setting
 * @package AppBundle\Controller
 */
class CMVSController extends Controller
{
    private $updateAll = 0;//覆盖更新
    private $systemTable = [
        //系统项目不允许覆盖
        "Role","User","UserGroups","UserGroupsRole","Admin","AdminMenu","AdminMenuUser","ConfCat","PlatConfig","Rules","RulesCategory",
        "UserLoginLog","UserInvite","WechatCode","WechatReply","UserInviteBonus"

    ];
    private $readyTable = [
        //以下项目已完成配置不允许再覆盖
        "Banners","ShopGoodsCategory","ShopGoods","UserLikesShop","ShopGoodsDivide","Orders","Province","City","Area","UserAddress","UserLikesProduct"
        ,"Money","MoneyLog","MoneyWait","MoneyWithdrawAccount","MoneyWithdrawLog"
        ,"UserLevelUp","UserLevelUpTask","OrderDeliver","AdminLog","UserDiyLevelUp","UserDiyLevelupLimit","Comments","ProductSellLog","AreaAgent","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa"
        ,"aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa","aaaaa"
    ];


    /**
     * @route("/cmvs",name="CMVSCAutoCreate")
     */
    public function autoCreate()
    {
//        $this->systemTable = [];
        $fromBundle = "AppBundle";
        $targetBundle = "AdminBundle";
        //0.创建目录
        $dirTemplate = str_replace("Controller","",__DIR__);//E:\WWW\models\src\AppBundle\
        $dir = str_replace($fromBundle,$targetBundle,$dirTemplate);//E:\WWW\models\src\AdminBundle\

        $dirEntity = $dir."Entity";is_dir($dirEntity) OR mkdir($dirEntity, 0777, true);
        $dirController = $dir."Controller";is_dir($dirController) OR mkdir($dirController, 0777, true);
        $dirControllerCommon = $dir."Controller\\AdminCommon";is_dir($dirControllerCommon) OR mkdir($dirControllerCommon, 0777, true);
        $dirControllerAdmin = $dir."Controller\\Admin";is_dir($dirControllerAdmin) OR mkdir($dirControllerAdmin, 0777, true);
        $dirSetting = $dir."Setting";is_dir($dirSetting) OR mkdir($dirSetting, 0777, true);
        $dirModel = $dir."Model";is_dir($dirModel) OR mkdir($dirModel, 0777, true);
        $dirModelCommon = $dir."Model\\Common";is_dir($dirModelCommon) OR mkdir($dirModelCommon, 0777, true);
        $dirTemplate = $dirTemplate."Template";is_dir($dirTemplate) OR mkdir($dirTemplate, 0777, true);

        //查找Entity
        $entityList = scandir($dirEntity);

//        var_dump($entityList);die();
        foreach ($entityList as $item) {
            $array = mb_split("\.",$item);
            if ($array[count($array) - 1] != "php") {
                continue;
            }
            $itemName = $array[0];

            //测试是否是Category类型的实体
            if (preg_match("/(.+)?Category/",$itemName) == 1) {//YY-mm-dd HH:ii:ss
                $isCat = "\\Category";
                $isCatTwig = "cat_";
            }else{
                $isCat = "";
                $isCatTwig = "";
            }

            var_dump($itemName);
            $tableNameTable = preg_replace("/([A-Z])/","_$1",substr($itemName,1));
            $tableNameTable = substr($itemName,0,1).$tableNameTable;
            var_dump($tableNameTable);

            if (in_array($itemName,$this->systemTable)){
                unlink($dirEntity."\\".$itemName.".php");
                continue;
            }
            if (in_array($itemName,$this->readyTable)){
//                unlink($dirEntity."\\".$itemName.".php");
                continue;
            }
            $entityName = "$targetBundle\\Entity\\".$itemName;
            $entity = new $entityName();
            $keys = $this->toArray($entity);
            array_shift($keys);

            //1.创建视图
            $dirView = $dir."Resources\\views\\".$itemName;is_dir($dirView) OR mkdir($dirView, 0777, true);
            var_dump($dirView);

            //2.创建Controller
            //检查文件是否存在
            $cTpl = file_get_contents($dirTemplate.$isCat."\\SAMPLEAdminCommonController.php");
            $cTpl = str_replace("__TARGET_BUNDLE__",$targetBundle,$cTpl);
            $cTpl = str_replace("__TARGET_ENTITY_TABLE__",$tableNameTable,$cTpl);
            $cTpl = str_replace("__TARGET_ENTITY__",$itemName,$cTpl);
            file_put_contents($dirControllerCommon."\\".$itemName."CommonController.php",$cTpl);
            if (!file_exists($dirControllerAdmin."\\".$itemName."Controller.php") || $this->updateAll){
                $cTpl = file_get_contents($dirTemplate.$isCat."\\SAMPLEAdminController.php");
                $cTpl = str_replace("__TARGET_BUNDLE__",$targetBundle,$cTpl);
                $cTpl = str_replace("__TARGET_ENTITY_TABLE__",$tableNameTable,$cTpl);
                $cTpl = str_replace("__TARGET_ENTITY__",$itemName,$cTpl);
                file_put_contents($dirControllerAdmin."\\".$itemName."Controller.php",$cTpl);
            }

            //3.创建Model
            $cTpl = file_get_contents($dirTemplate.$isCat."\\SAMPLECommonModel.php");
            $cTpl = str_replace("__TARGET_BUNDLE__",$targetBundle,$cTpl);
            $cTpl = str_replace("__TARGET_ENTITY__",$itemName,$cTpl);
            file_put_contents($dirModelCommon."\\".$itemName."CommonModel.php",$cTpl);
            if (!file_exists($dirModel."\\".$itemName."Model.php") || $this->updateAll){
                $cTpl = file_get_contents($dirTemplate.$isCat."\\SAMPLEModel.php");
                $cTpl = str_replace("__TARGET_BUNDLE__",$targetBundle,$cTpl);
                $cTpl = str_replace("__TARGET_ENTITY_TABLE__",$tableNameTable,$cTpl);
                $cTpl = str_replace("__TARGET_ENTITY__",$itemName,$cTpl);
                file_put_contents($dirModel."\\".$itemName."Model.php",$cTpl);
            }


            //4-5：处理entity内部字段
//            var_dump($keys);
            $formConfStr = "";
            $listConfArray = ["'id'"];
            $viewConfTitleStr = "";
            $viewConfRowStr = "";
            foreach ( $keys as $k => $v ) {
                $V = new ViewsInList();
                $dataConf = $V->setItem($k,$itemName)->get();
                var_dump($dataConf);
                //select 字段生成
                $listConfArray[] = "'".$k."'";
                //管理列表title生成
                $viewConfTitleStr .= $V->createViewTitle($dataConf);
                //管理列表Row生成
                $viewConfRowStr .= $V->createViewRow($dataConf,$itemName);
                //form编辑字段生成
                $formConfStr .= $V->createAddItem($dataConf);
            }
            $listConfStr = implode(",",$listConfArray);
            $V = new ViewsInList();
            $viewConfTitleStr = $V->createViewHeadAndTail($viewConfTitleStr);
            $viewConfRowStr = $V->createViewRowHeadAndTail($viewConfRowStr,$itemName);



            //4.创建Setting
            if (!file_exists($dirSetting."\\".$itemName."Setting.php") || $this->updateAll){
                $cTpl = file_get_contents($dirTemplate.$isCat."\\SAMPLESetting.php.txt");
                $cTpl = str_replace("__TARGET_BUNDLE__",$targetBundle,$cTpl);
                $cTpl = str_replace("__TARGET_ENTITY__",$itemName,$cTpl);
                $cTpl = str_replace("__TARGET_ENTITY_TABLE__",$tableNameTable." AS ".$itemName,$cTpl);
                $cTpl = str_replace("__TARGET_TABLE__",$tableNameTable,$cTpl);
                $cTpl = str_replace("__FORM_CONF__",$formConfStr,$cTpl);
                $cTpl = str_replace("__LIST_CONF__",$listConfStr,$cTpl);
                file_put_contents($dirSetting."\\".$itemName."Setting.php",$cTpl);
            }
            //5.创建View
            $cTpl = file_get_contents($dirTemplate.$isCat."\\list.php.twig");
            $cTpl = str_replace("__TARGET_BUNDLE__",$targetBundle,$cTpl);
            $cTpl = str_replace("__TARGET_ENTITY_TABLE__",$tableNameTable,$cTpl);
            $cTpl = str_replace("__TARGET_ENTITY__",$itemName,$cTpl);
            $cTpl = str_replace("__LIST_TITLE_CONF__",$viewConfTitleStr,$cTpl);
            $cTpl = str_replace("__LIST_ROW_CONF__",$viewConfRowStr,$cTpl);
            file_put_contents($dirView."\\{$isCatTwig}list.php.twig",$cTpl);
        }

    }
    /**
     * @param $entity
     * @return array
     */
    private  function toArray(&$entity)
    {
        if(!$entity) return[];
        $methods = (get_class_methods(get_class($entity)));
        $arrData = array();
        foreach ($methods as $method) {
            $attr = lcfirst(substr($method,3));
            $funcName = "get".ucfirst($attr);
            $arrData[$attr] = $entity->$funcName();
        }
        $entity = $arrData;
        return $arrData;
    }
    public function createAddItem($conf)
    {

    }
}
